package com.tanhua.sso.service;

import com.tanhua.common.vo.ErrorResult;
import com.tanhua.sso.config.AliyunSMSConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * @Author 王加鑫
 * @Date 2021/08/31 20:10
 * @Since JDK 1.8
 */
@Service
@Slf4j
public class SmsService {

    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送短信验证码
     */
    public String sendSms(String mobile) {
        String s = null;
        if(null != mobile){
//            s = RandomUtils.nextInt(100000,999999) + "";
            s = "123456";
        }
        return s;
    }

    /**
     * 将验证码保存到redis中并且判断发送是否出现问题
     */
    public ErrorResult sendCheckCode(String phone) {
        //1、首先要判断redis中是否存储了该验证码
        String redisKey = "CHECK_CODE" + phone;
        if(redisTemplate.hasKey(redisKey)){
            //说明验证码还未失效！
            return ErrorResult.builder().errCode("000001").errMessage("该验证码还未失效！！！").build();
        }
        String code = sendSms(phone);
        //2、判断验证码是否有效
        if(StringUtils.isEmpty(code)){
            return ErrorResult.builder().errCode("000001").errMessage("验证码发送失败").build();
        }
        //3、走到这说明redis中未存有该验证码，将其添加到redis中,并且设置有效期为5分钟 Duration.ofMinutes(5)
        redisTemplate.opsForValue().set(redisKey,code, Duration.ofMinutes(5));
        return null;
    }

}
